// 引入mongoose
const mongoose = require('mongoose')
// 引入md5加密
const md5 = require('md5')
// 引入UserModel表
const UserModel = require('./models/UserModel')


module.exports = () => {
    const promise = mongoose.connect('mongodb://localhost:27017/user_manage')

    mongoose.connection.on('open', async () => {
        console.log('数据库连接成功~');
        // 判断是否有admin用户，如果没有就创建
        const user = await UserModel.findOne({
            username: 'admin'
        })
        if (!user) {
            UserModel.create({
                username: 'admin',
                pwd: md5('123456'),
                profile: '/upload/29cd18633dcb1e62b2917e000.png.jpg'
            })
        }
    })

    mongoose.connection.on('error', () => {
        console.log('数据库连接失败!');
    })

    return promise
}